package com.dmj.sqldsl.executor.visitor;

import com.dmj.sqldsl.executor.exception.DeleteParseException;
import com.dmj.sqldsl.model.DslUpdate;
import com.dmj.sqldsl.model.Set;
import com.dmj.sqldsl.model.column.SubQueryValueColumn;
import com.dmj.sqldsl.model.table.SubQueryTable;
import lombok.AllArgsConstructor;
import java.util.List;
import java.util.stream.Collectors;

@AllArgsConstructor
public class UpdateModelVisitor extends ModelVisitor {

  private final QueryModelVisitor queryModelVisitor;

  public String visit(DslUpdate update) {
    String table = visit(update.getTable());
    String sets = visit(update.getSets());
    String where = visit(update.getWhere());
    return String.format("update %s set %s%s", table, sets, where);
  }

  protected String visit(List<Set> sets) {
    return sets.stream().map(this::visit).collect(Collectors.joining(","));
  }

  protected String visit(Set set) {
    params.add(new Parameter(set.getRight().getValue()));
    return String.format("%s=?", set.getLeft().getColumnName());
  }

  @Override
  protected String visit(SubQueryValueColumn column) {
    return queryModelVisitor.visit(column);
  }

  @Override
  protected String visit(SubQueryTable table) {
    throw new DeleteParseException("Unsupported delete sql with sub query table!");
  }
}
